﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.SystemModule;
using EasyXaf.EntityDesigner.BusinessObjects.Enums;
using System.ComponentModel;

namespace EasyXaf.EntityDesigner.Controllers;

public class EnumListViewController : ObjectViewController<ListView, Enumeration>
{
    private NewObjectViewController _newObjectViewController;
    private ListViewProcessCurrentObjectController _listViewProcessCurrentObjectController;

    public EnumListViewController()
    {
        TargetViewId = "Enumeration_Management_ListView";
    }

    protected override void OnActivated()
    {
        base.OnActivated();

        _newObjectViewController = Frame.GetController<NewObjectViewController>();
        if (_newObjectViewController != null)
        {
            _newObjectViewController.Active[Name] = false;
        }

        _listViewProcessCurrentObjectController = Frame.GetController<ListViewProcessCurrentObjectController>();
        if (_listViewProcessCurrentObjectController != null)
        {
            _listViewProcessCurrentObjectController.CustomHandleProcessSelectedItem += ListViewProcessCurrentObjectController_CustomHandleProcessSelectedItem;
        }
    }

    protected override void OnDeactivated()
    {
        _newObjectViewController?.Active.RemoveItem(Name);

        base.OnDeactivated();
    }

    private void ListViewProcessCurrentObjectController_CustomHandleProcessSelectedItem(object sender, HandledEventArgs e)
    {
        var nestedObjectSpace = Application.CreateNestedObjectSpace(ObjectSpace);
        var enumeration = nestedObjectSpace.GetObject(ViewCurrentObject);
        var view = Application.CreateDetailView(nestedObjectSpace, enumeration);

        void ObjectSpace_Committed(object sender, EventArgs e)
        {
            ((INestedObjectSpace)nestedObjectSpace).ParentObjectSpace.CommitChanges();
        }

        Application.ShowViewStrategy.ShowViewInPopupWindow(view, () =>
        {
            view.ObjectSpace.Committed -= ObjectSpace_Committed;
            view.ObjectSpace.Committed += ObjectSpace_Committed;
        });

        e.Handled = true;
    }
}
